﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 六轴的类型
/// </summary>
public enum AxisType
{
    normal,
    up,
    down,
    left,
    right,
    forword,
    back

}
public class SquareRotateController : MonoBehaviour {
    #region   所有定义
    public GameObject MagicCube;//名字为 MoFang的GameObject
    private GameObject[] cubes;//定义所有cube的数组

    private float rotateTime = 0; //转动时的递增值的临时变量//
    private float rotateSpeed = 2f;//旋转的速度

    private Vector3 axisPos; //魔方某层转动时的转动轴//
    private bool isRotate = false; //某层是否可转动//

    private GameObject sphere;//小球
    private MoveController spherMove;//小球移动脚本

    public bool isHasColor = true;//射到的面有没有颜色
    private bool isOneStep = true;//控制再次按下时间
    private bool YesOrNo = false;//控制是否进入导航条件
    private Vector3 tempPos;//获取射到的物体的位置
    private float xDistance;//记录x轴移动的距离
    private float zDistance;//记录z轴移动的距离
    public GameObject wall;//获取墙
    private SquareColorController sCC;//获取墙的脚本
    private GameObject hitTemp;//临时的射到的物体

    private bool triggerTrap;//是否触发陷阱

    public int disAppearStepNumber = 5;//魔心未出现步数
    public int appearStepNumber = 20;//魔心出现步数
    #endregion
    #region 定义： 找到六个轴 
    public GameObject upAxis;
    public GameObject downAxis;
    public GameObject leftAxis;
    public GameObject rightAxis;
    public GameObject forwordAxis;
    public GameObject backAxis;
    #endregion
    void Start()
    {
        cubes = GameObject.FindGameObjectsWithTag("Cube");//找到所有cube
        sCC = wall.GetComponent<SquareColorController>();

        sphere = GameObject.FindGameObjectWithTag("Sphere");//找到小球
        spherMove = sphere.GetComponent<MoveController>();//找到小球脚本

        #region 设置六个面的转动轴的枚举值
        upAxis.GetComponent<CubeAxisType>().type = AxisType.up;
        downAxis.GetComponent<CubeAxisType>().type = AxisType.down;
        leftAxis.GetComponent<CubeAxisType>().type = AxisType.left;
        rightAxis.GetComponent<CubeAxisType>().type = AxisType.right;
        forwordAxis.GetComponent<CubeAxisType>().type = AxisType.forword;
        backAxis.GetComponent<CubeAxisType>().type = AxisType.back;
        #endregion
    }
    void Update()
    {
        ShootRay();
        Trap();
        IsRotate();
    }
    /// <summary>
    /// 发射射线确定小球移动位置
    /// </summary>
    void ShootRay()
    {
        if (Input.GetMouseButtonDown(0) && isOneStep)//按下
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//发射线
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))//获取射到的物体
            {
                if (hit.transform.CompareTag("CubePlane"))//如果是面
                {
                    tempPos = hit.transform.position;//记录射到的物体的位置
                    hitTemp = hit.transform.gameObject;
                    //如果射到的平面没有颜色而且距离为1
                    if (Mathf.Abs(sphere.transform.position.x - tempPos.x) < 2f && Mathf.Abs(sphere.transform.position.z - tempPos.z) <= 0.2f && !sCC.HasColor(hit.transform.gameObject))//
                    {//判断是 x轴上的移动
                        xDistance = tempPos.x - sphere.transform.position.x;//记录x距离
                        zDistance = tempPos.z - sphere.transform.position.z;//记录z距离
                        isOneStep = false;//已进行点击 不可再次点击
                        spherMove.MoveAgent(tempPos);//赋予小球的导航点
                        if (disAppearStepNumber > 0)
                        {
                            disAppearStepNumber -= 1;
                        }
                        else
                        {
                            appearStepNumber -= 1;
                        }
                        Invoke("YESORNO", 0.02f);//此时可以进行判断是否到达导航点
                    }
                    else if (Mathf.Abs(sphere.transform.position.x - tempPos.x) <= 0.2f && Mathf.Abs(sphere.transform.position.z - tempPos.z) < 2f && !sCC.HasColor(hit.transform.gameObject))// 
                    {//判断是 z轴上的移动
                        xDistance = tempPos.x - sphere.transform.position.x;//记录x距离
                        zDistance = tempPos.z - sphere.transform.position.z;//记录z距离
                        isOneStep = false;//已进行点击 不可再次点击
                        spherMove.MoveAgent(tempPos);//赋予小球的导航点
                        if (disAppearStepNumber > 0)
                        {
                            disAppearStepNumber -= 1;
                        }
                        else
                        {
                            appearStepNumber -= 1;
                        }
                        Invoke("YESORNO", 0.02f);//此时可以进行判断是否到达导航点
                    }
                }
            }
        }
        if (spherMove.IsOver() && YesOrNo)
        {
            sCC.ChangeColor(hitTemp);
            YesOrNo = false;//限制执行
            if (zDistance >= 0.9f && Mathf.Abs(xDistance) <= 0.2f)//向前走 后面旋转
            {
                SquareRotate(backAxis.GetComponent<CubeAxisType>().type, backAxis);
            }
            else if (zDistance <= -0.9f && Mathf.Abs(xDistance) <= 0.2f)//向后走 前面旋转
            {
                SquareRotate(forwordAxis.GetComponent<CubeAxisType>().type, forwordAxis);
            }
            else if (xDistance >= 0.9f && Mathf.Abs(zDistance) <= 0.2f)//向右走 左面旋转
            {
                SquareRotate(leftAxis.GetComponent<CubeAxisType>().type, leftAxis);
            }
            else if (xDistance <= -0.9f && Mathf.Abs(zDistance) <= 0.2f)//向左走 右面旋转
            {
                SquareRotate(rightAxis.GetComponent<CubeAxisType>().type, rightAxis);
            }
        }
    }

    /// <summary>
    /// 协助导航判断 延迟一帧
    /// </summary>
    void YESORNO()
    {
        YesOrNo = true;
    }

    /// <summary>
    /// 触发陷阱方法
    /// </summary>
    void Trap()
    {
        if (triggerTrap)
        {
            isOneStep = false;
            SquareRotate(upAxis.GetComponent<CubeAxisType>().type, upAxis);
            SquareRotate(downAxis.GetComponent<CubeAxisType>().type, downAxis);
        }
    }

    /// <summary>
    /// 魔方旋转  分六方向
    /// </summary>
    void SquareRotate(AxisType type, GameObject cube)
    {
        //左右分辨为x  0  左为-
        //前后分辨为z  2  后为-
        //上下分辨为y  1  下为-
        switch (type)
        {
            case AxisType.up:
                {
                    LinkAxis(1, cube);
                    axisPos = Vector3.up;
                    break;
                }
            case AxisType.down:
                {
                    LinkAxis(1, cube);
                    axisPos = (Vector3.down);
                    break;
                }
            case AxisType.left:
                {
                    LinkAxis(0, cube);
                    axisPos = (Vector3.left);
                    break;
                }
            case AxisType.right:
                {
                    LinkAxis(0, cube);
                    axisPos = (Vector3.right);
                    break;
                }
            case AxisType.forword:
                {
                    LinkAxis(2, cube);
                    axisPos = (Vector3.forward);
                    break;
                }
            case AxisType.back:
                {
                    LinkAxis(2, cube);
                    axisPos = (Vector3.back);
                    break;
                }
            default:
                { break; }
        }
    }

    /// <summary>
    /// 找到转动轴  让轴带动同一面上所有的cube旋转
    /// </summary>
    /// <param name="point">x，y，z 中的一个（0，1，2）</param>
    /// <param name="cubeAxis">转动轴</param>
    void LinkAxis(int point, GameObject cubeAxis)
    {
        //找出转动轴后将要转动的层添加到这个物体上，用这个物体的转动带动这一层//
        float cubeAxisPoint = cubeAxis.transform.position[point];
        foreach (GameObject cube in cubes)//获取所有的cube
        {
            float cubePoint = cube.transform.position[point];//获取单个坐标
            if (Mathf.Abs(cubePoint - cubeAxisPoint) < 0.1f)//判断是否是一面
            {
                cube.transform.parent = gameObject.transform;//是，就为子级  
            }
        }
        isRotate = true;
    }

    /// <summary>
    /// 旋转
    /// </summary>
    void IsRotate()
    {
        if (isRotate)//转动相应的层//
        {
            rotateTime += Time.deltaTime * rotateSpeed;//记录旋时间
            Vector3 rotate = axisPos * Mathf.Clamp01(rotateTime) * 90;//每次转动90度
            transform.eulerAngles = rotate;//转动角度赋值
            if (rotateTime >= 1f)
            {
                rotateTime = 0;
                foreach (GameObject cube in cubes)//重新将所有的cube父级设置为MoFang 为下次旋转做准备
                {
                    cube.transform.parent = MagicCube.transform;
                    cube.transform.localScale = Vector3.one;//初始化大小 防止意外发生
                }
                transform.rotation = Quaternion.identity;//清零旋转
                isOneStep = true;//旋转完毕可以再次点击
                isRotate = false;//关闭旋转
            }
        }
    }
}
